<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    width="50%"
    :before-close="handleClose"
  >
    <el-form ref="ruleForm" :model="formData" :rules="rules" style="text-align: center" :inline="true" label-width="80px" label-position="right" size="small">
      <el-upload
        class="avatar-uploader"
        :disabled="isEdit === 'view'"
        action=""
        :show-file-list="false"
        :http-request="uploadAvatar"
        :before-upload="beforeUploadAvatar"
      >
        <img v-if="formData.avatar" :src="formData.avatarUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon" />
      </el-upload>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" :disabled="isEdit === 'view'||isEdit === 'edit'" placeholder="请输入用户名" clearable />
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="formData.name" :disabled="isEdit === 'view'" placeholder="请输入姓名" clearable />
      </el-form-item>
      <el-form-item label="邮箱地址" prop="email">
        <el-input v-model="formData.email" :disabled="isEdit === 'view'" placeholder="请输入邮箱地址" clearable />
      </el-form-item>
      <el-form-item label="手机号码" prop="mobile">
        <el-tooltip class="item" effect="dark" content="可用于系统登陆" placement="right">
          <el-input v-model="formData.mobile" :disabled="isEdit === 'view'" placeholder="请输入手机号码" clearable />
        </el-tooltip>
      </el-form-item>
      <el-form-item label="职位名称">
        <el-input v-model="formData.position" :disabled="isEdit === 'view'" placeholder="请输入职位名称" clearable />
      </el-form-item>
      <el-form-item label="账户状态" prop="is_active">
        <el-select v-model="formData.is_active" :disabled="isEdit === 'view'" placeholder="请选择账户状态">
          <el-option
            v-for="item in enabledTypeOptions"
            :key="item.key"
            :label="item.display_name"
            :value="item.key"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属组织">
        <el-cascader
          v-model="formData.department"
          :options="treeOrganization"
          :props="{ expandTrigger: 'hover', checkStrictly: true, label: 'label', value: 'id', children: 'children' }"

          :disabled="isEdit === 'view'"
          placeholder="请选择部门/可搜索"
          :show-all-levels="false"
          filterable
          clearable
        />
      </el-form-item>
      <el-form-item label="上级主管">
        <el-tooltip class="item" effect="dark" placement="right">
          <div slot="content">注：如果上级主管的部门项为空，则不会在此显示</div>
          <div slot="content">需为上级主管选择所属部门</div>
          <el-cascader
            v-model="formData.superior"
            :options="treeOrganizationUser"
            :props="{ expandTrigger: 'hover', label: 'label', value: 'id', children: 'children' }"
            :disabled="isEdit === 'view'"
            placeholder="请选择上级主管/可搜索"
            :show-all-levels="false"
            filterable
            clearable
          />
        </el-tooltip>
      </el-form-item>
      <el-form-item label="角色权限" prop="roles">
        <el-cascader
          v-model="formData.roles"
          :options="treeRole"
          :props="{ expandTrigger: 'hover', label: 'label', value: 'id', children: 'children', multiple: true }"
          :disabled="isEdit === 'view'"
          placeholder="请选择角色/可搜索"
          :show-all-levels="false"
          filterable
          clearable
        />
      </el-form-item>
      <el-form-item label="描述说明" prop="introduction">
        <el-input v-model="formData.introduction" type="textarea" :rows="1" :disabled="isEdit === 'view'" style="width: 199px;" placeholder="用户描述说明" />
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose" v-text="isBtnCloseTitle" />
      <el-button v-show="isEdit !== 'view'" type="primary" @click="SubmitForm" v-text="isBtnConfTitle" />
    </span>
  </el-dialog>
</template>

<script>
import { addUser, checkMobile, checkUsername, editUser, viewUser, uploadUserAvatar } from '../../../../api/user'
import { treeOrganization, treeOrganizationUser, treeRole } from '../../../../api/tree'

export default {
  // 接收父组件传递过来的值
  props: {
    vdialog: {
      type: Boolean,
      default: false
    },
    vtitle: {
      type: String,
      default: ''
    },
    visedit: {
      type: String,
      default: ''
    },
    vformid: {
      // 接收父组件传过来的ID
      type: Number,
      default: 0
    }
  },
  data() {
    // 校验用户名与手机号是否存在 rule对应rules, value对应username，callback对应返回信息
    const rulesCheckUsername = (rule, value, callback) => {
      if (this.visedit === 'edit') {
        callback()
      }
      checkUsername({ username: this.formData.username }).then((res) => {
        if (res.exists && res.code === 200) {
          callback(new Error(res.message))
          return
        } else {
          callback()
        }
      })
    }
    const rulesCheckMobile = (rule, value, callback) => {
      checkMobile({ username: this.formData.username, mobile: this.formData.mobile }).then((res) => {
        if (res.exists && res.code === 200) {
          callback(new Error(res.message))
          return
        } else {
          callback()
        }
      })
    }
    return {
      // 控制弹出框的显示与隐藏
      dialogVisible: false,
      title: '',
      isBtnCloseTitle: '',
      isBtnConfTitle: '',
      enabledTypeOptions: [
        { key: true, display_name: '激活' },
        { key: false, display_name: '锁定' }
      ],
      formDataBak: '',
      formData: {
        avatar: '',
        avatarUrl: '',
        username: '',
        name: '',
        email: '',
        mobile: '',
        position: '',
        is_active: false,
        department: '',
        superior: '',
        roles: [],
        introduction: ''
      },
      isEdit: '',
      formId: '',
      treeOrganization: [],
      treeRole: [],
      treeOrganizationUser: [],
      // rules 表单前验证
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, message: '请输入不少于2个字符的用户名', trigger: 'blur' },
          { validator: rulesCheckUsername, trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, message: '请输入不少于2个字符的姓名', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱地址不能为空', trigger: 'blur' },
          { pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: '邮箱地址必须符合规范!', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { pattern: /^[1][35789]\d{9}$/, message: '手机号必须符合规范!', trigger: 'blur' },
          { validator: rulesCheckMobile, trigger: 'blur' }
        ],
        is_active: [
          { required: true, message: '状态必选一项', trigger: 'blur' }
        ],
        roles: [
          { required: true, message: '请选择角色', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    // 监听 父组件传递过来的props内的值并改变/赋值
    vdialog() {
      // dialogVisible 弹框的显示与隐藏
      this.dialogVisible = this.vdialog
      if (this.dialogVisible) {
        // formid 数据ID
        this.formid = this.vformid
        // isEdit 表单状态
        this.isEdit = this.visedit
        // title 弹框的标题
        this.title = this.vtitle
        // isTree 获取目录树数据
        this.isTree()
        // 状态判断
        if (this.isEdit === 'view') {
          this.isBtnCloseTitle = '关闭'
          this.viewForm()
        } else if (this.isEdit === 'add') {
          this.isBtnCloseTitle = '取消'
          this.isBtnConfTitle = '新增'
        } else if (this.isEdit === 'edit') {
          this.isBtnCloseTitle = '取消'
          this.isBtnConfTitle = '编辑'
          this.viewForm()
        }
      }
    }
  },
  methods: {
    viewForm() {
      viewUser(this.formid).then(res => {
        this.formDataBak = JSON.parse(JSON.stringify(res.data))
        this.formData.avatarUrl = process.env.VUE_APP_BASE_API + res.data.avatar
        this.formData.avatar = res.data.avatar
        this.formData.username = res.data.username
        this.formData.name = res.data.name
        this.formData.email = res.data.email
        this.formData.mobile = res.data.mobile
        this.formData.position = res.data.position
        this.formData.is_active = res.data.is_active
        this.formData.department = res.data.department
        this.formData.superior = res.data.superior
        this.formData.roles = res.data.roles
        this.formData.introduction = res.data.introduction
      })
    },
    SubmitForm() {
      // 表单验证并新增/编辑
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          // 判断目录树是否有数据，有则截取数值 (由于组织架构过长，这里需要修改)
          if (this.formData.department === null || this.formData.department.length === 0) {
            this.formData.department = ''
          } else {
            this.formData.department = this.formData.department.pop()
          }
          if (this.formData.superior === null || this.formData.superior.length === 0) {
            this.formData.superior = ''
          } else {
            this.formData.superior = this.formData.superior.pop()
          }
          if (this.formData.roles) {
            this.formData.roles = this.formData.roles.map(v => v.pop())
          }

          if (this.isEdit === 'add') {
            this.addForm()
          } else if (this.isEdit === 'edit') {
            this.editForm()
          } else {
            this.$notify.warning({
              type: 'warning',
              title: '警告',
              message: '表单非法操作',
              showClose: true,
              duration: 0
            })
          }
        }
      })
    },
    addForm() {
      if (this.formData.avatar === '') {
        this.formData.avatar = 'media/image/default.gif'
      }
      addUser(this.formData).then((res) => {
        this.$notify.success({
          type: 'success',
          title: '成功',
          message: res.message + ' 默认密码为【 123456 】  ( 请提醒用户尽快修改密码 )',
          showClose: true,
          duration: 5 * 1000
        })
        this.isEditStatus()
        // $parent 子组件调用父组件方法
        this.$parent.getList()
      })
    },
    editForm() {
      editUser(this.formid, this.formData).then((res) => {
        this.$notify.success({
          type: 'success',
          title: '成功',
          message: '编辑用户【 ' + this.formData.username + ' 】',
          showClose: true,
          duration: 5 * 1000
        })
        this.isEditStatus()
        // $parent 子组件调用父组件方法
        this.$parent.getList()
      })
    },
    // 选择头像后点击确定后触发的事件
    beforeUploadAvatar(file) {
      const isLt2M = file.size / 1024 / 1024 < 10

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 10MB!')
      }
      return isLt2M
    },
    uploadAvatar(file) {
      // 定义一个FormData类
      const AvatarFile = new FormData()
      // 把照片传进去
      AvatarFile.append('avatar', file.file)
      // 发起请求
      uploadUserAvatar(AvatarFile).then((res) => {
        this.formData.avatar = res.data.name
        this.formData.avatarUrl = process.env.VUE_APP_BASE_API + res.data.name
      })
    },
    // 弹出框关闭后的函数
    handleClose(done) {
      // 子组件调用父组件方法，并传递参数 this.$emit('父组件的方法', '传递的参数')
      if (this.isEdit === 'view') {
        this.isEditStatus()
      } else {
        if (this.formData.username) {
          this.$confirm('确认取消/关闭？')
            .then(_ => {
              this.isEditStatus()
              done()
            })
            .catch(_ => {})
        } else {
          this.isEditStatus()
        }
      }
    },
    isEditStatus() {
      // this.$refs['form表单里面的ref值'].resetFields()
      this.$refs['ruleForm'].resetFields()
      this.formData = { avatarUrl: '', avatar: '', username: '', name: '', email: '', mobile: '', position: '', is_active: false, department: '', superior: '', roles: [], introduction: '' }
      this.$emit('changeShow', 'false', 0)
    },
    // 弹出框关闭后的函数
    // cascade 级联选择器 目录树
    isTree() {
      treeOrganization().then((res) => {
        this.treeOrganization = res.data
      })
      treeRole().then((res) => {
        this.treeRole = res.data
      })
      treeOrganizationUser().then((res) => {
        this.treeOrganizationUser = res.data
      })
    }
    // cascade 级联选择器 目录树
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    margin: 20px;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
